package com.ruoyi.audit.service.impl;

import java.util.*;

import com.ruoyi.appointment.domain.BusServiceItem;
import com.ruoyi.appointment.domain.vo.BusServiceItemVo;
import com.ruoyi.appointment.enums.ServiceItemAuditStatusEnum;
import com.ruoyi.appointment.service.IBusServiceItemService;
import com.ruoyi.audit.domain.vo.HandleAuditParam;
import com.ruoyi.audit.domain.vo.StartAuditParam;
import com.ruoyi.audit.enums.BpmnTypeEnum;
import com.ruoyi.audit.enums.CarPackageAuditStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.flow.domain.BusBpmnInfo;
import com.ruoyi.flow.service.IBusBpmnInfoService;
import com.ruoyi.flow.service.IProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.audit.mapper.BusCarPackageAuditMapper;
import com.ruoyi.audit.domain.BusCarPackageAudit;
import com.ruoyi.audit.service.IBusCarPackageAuditService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 审核信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-02
 */
@Service
public class BusCarPackageAuditServiceImpl implements IBusCarPackageAuditService {
    @Autowired
    private BusCarPackageAuditMapper busCarPackageAuditMapper;
    @Autowired
    private IBusServiceItemService busServiceItemService;
    @Autowired
    private IBusBpmnInfoService bpmnInfoService;
    @Autowired
    private IProcessService processService;

    /**
     * 查询审核信息
     *
     * @param id 审核信息主键
     * @return 审核信息
     */
    @Override
    public BusCarPackageAudit selectBusCarPackageAuditById(Long id) {
        return busCarPackageAuditMapper.selectBusCarPackageAuditById(id);
    }

    /**
     * 查询审核信息列表
     *
     * @param busCarPackageAudit 审核信息
     * @return 审核信息
     */
    @Override
    public List<BusCarPackageAudit> selectBusCarPackageAuditList(BusCarPackageAudit busCarPackageAudit) {

        return busCarPackageAuditMapper.selectBusCarPackageAuditList(busCarPackageAudit);
    }

    /**
     * 新增审核信息
     *
     * @param busCarPackageAudit 审核信息
     * @return 结果
     */
    @Override
    public int insertBusCarPackageAudit(BusCarPackageAudit busCarPackageAudit) {
        busCarPackageAudit.setCreateTime(DateUtils.getNowDate());
        return busCarPackageAuditMapper.insertBusCarPackageAudit(busCarPackageAudit);
    }

    /**
     * 修改审核信息
     *
     * @param busCarPackageAudit 审核信息
     * @return 结果
     */
    @Override
    public int updateBusCarPackageAudit(BusCarPackageAudit busCarPackageAudit) {
        return busCarPackageAuditMapper.updateBusCarPackageAudit(busCarPackageAudit);
    }

    /**
     * 批量删除审核信息
     *
     * @param ids 需要删除的审核信息主键
     * @return 结果
     */
    @Override
    public int deleteBusCarPackageAuditByIds(Long[] ids) {
        return busCarPackageAuditMapper.deleteBusCarPackageAuditByIds(ids);
    }

    /**
     * 删除审核信息信息
     *
     * @param id 审核信息主键
     * @return 结果
     */
    @Override
    public int deleteBusCarPackageAuditById(Long id) {
        return busCarPackageAuditMapper.deleteBusCarPackageAuditById(id);
    }

    /**
     * 开始审核服务项
     *
     * @param startAuditParam
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startAudit(StartAuditParam startAuditParam) {
        BusServiceItem busServiceItem = busServiceItemService.selectBusServiceItemById(startAuditParam.getServiceItemId());
        Assert.notNull(busServiceItem, "参数错误，找不到服务项");
        Assert.state(BusServiceItemVo.PACKAGE_YES.equals(busServiceItem.getCarPackage()) &&
                        Long.valueOf(BusServiceItemVo.SALI_NO).equals(busServiceItem.getSaleStatus()) &&
                        (ServiceItemAuditStatusEnum.INITIALING.ordinal() == (busServiceItem.getAuditStatus()) || ServiceItemAuditStatusEnum.REJECTED.ordinal() == busServiceItem.getAuditStatus())
                , "非法状态，不能发起审核");
        BusCarPackageAudit busCarPackageAudit = buildAudit(busServiceItem, startAuditParam);
        insertBusCarPackageAudit(busCarPackageAudit);
        BusBpmnInfo busBpmnInfo = bpmnInfoService.selectLastestInfoByType(BpmnTypeEnum.CAR_PACKAGE.ordinal());
        Map<String, Object> variables = new HashMap<>();
        variables.put("discountAmount", busServiceItem.getDiscountPrice().longValue() + "");
        variables.put("shopOwnerId", startAuditParam.getShopOwnerId());
        variables.put("financeId", startAuditParam.getFinancialId());
        String instanceId = processService.startProcessInstance(busBpmnInfo.getProcessDefinitionKey(), busCarPackageAudit.getId() + "", variables);
        busCarPackageAudit.setInstanceId(instanceId);
        updateBusCarPackageAudit(busCarPackageAudit);
        busServiceItemService.updateAuditStatus(busServiceItem.getId(), ServiceItemAuditStatusEnum.AUDITING.ordinal());

    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int cancelAuditById(Long id) {
        BusCarPackageAudit busCarPackageAudit = selectBusCarPackageAuditById(id);
        Assert.notNull(busCarPackageAudit, "参数错误，套餐不存在");
        Assert.state(busCarPackageAudit.getStatus() == CarPackageAuditStatusEnum.AUDITING.ordinal(), "只有审核中允许撤销");
        busCarPackageAuditMapper.updateStatus(id, CarPackageAuditStatusEnum.CANCELED.ordinal());
        processService.deleteProcessInstance(busCarPackageAudit.getInstanceId(), "[" + SecurityUtils.getUsername() + "]撤销审核");
        busServiceItemService.updateAuditStatus(busCarPackageAudit.getServiceItemId(), ServiceItemAuditStatusEnum.INITIALING.ordinal());
        return 1;
    }

    /**
     * 查询待办审核
     *
     * @return
     */
    @Override
    public List<BusCarPackageAudit> selectAuditTodoList() {
        BusBpmnInfo busBpmnInfo = bpmnInfoService.selectLastestInfoByType(BpmnTypeEnum.CAR_PACKAGE.ordinal());
        PageUtils.startPage();
        List<String> businessKeyList = processService.selectBusinessKeyList(busBpmnInfo.getProcessDefinitionKey(), SecurityUtils.getUserId());
        if (CollectionUtils.isEmpty(businessKeyList)) {
            return Collections.emptyList();
        }
        List<BusCarPackageAudit> list = busCarPackageAuditMapper.selectBusCarPackageAuditByIds(businessKeyList);
        return list;

    }

    /**
     * 审批功能
     *
     * @param handleAuditParam
     */
    @Override
    public void handleAudit(@RequestBody HandleAuditParam handleAuditParam) {
        BusCarPackageAudit busCarPackageAudit = selectBusCarPackageAuditById(handleAuditParam.getAuditId());
        Assert.notNull(busCarPackageAudit, "参数错误，审核对象不存在");
        Assert.state(CarPackageAuditStatusEnum.AUDITING.ordinal() == busCarPackageAudit.getStatus(), "非法状态");
        Boolean ended = processService.handleTaskByInstanceIdAndAssignee(busCarPackageAudit.getInstanceId(), SecurityUtils.getUserId(), handleAuditParam);
        if (ended) {
            busCarPackageAuditMapper.updateStatus(handleAuditParam.getAuditId(), (handleAuditParam.isPassed() ? CarPackageAuditStatusEnum.PASSED.ordinal() : CarPackageAuditStatusEnum.REJECTED.ordinal()));
            busServiceItemService.updateAuditStatus(busCarPackageAudit.getServiceItemId(), (handleAuditParam.isPassed() ? ServiceItemAuditStatusEnum.PASSED.ordinal() : ServiceItemAuditStatusEnum.REJECTED.ordinal()));
        }
    }

    /**
     * 查询我的已办
     *
     * @return
     */
    @Override
    public List<BusCarPackageAudit> selectAuditDoneList() {
        BusBpmnInfo busBpmnInfo = bpmnInfoService.selectLastestInfoByType(BpmnTypeEnum.CAR_PACKAGE.ordinal());
        Long userId = SecurityUtils.getUserId();
        List<String> businessKeyList = processService.selectHistoryBusinessKeyList(busBpmnInfo, userId);
        if (CollectionUtils.isEmpty(businessKeyList)) {
            return Collections.emptyList();
        }
        PageUtils.startPage();
        return busCarPackageAuditMapper.selectBusCarPackageAuditByIds(businessKeyList);
    }

    public BusCarPackageAudit buildAudit(BusServiceItem busServiceItem, StartAuditParam param) {
        BusCarPackageAudit busCarPackageAudit = new BusCarPackageAudit();
        busCarPackageAudit.setCreateorId(SecurityUtils.getUserId() + "");
        busCarPackageAudit.setInfo(param.getInfo());
        busCarPackageAudit.setServiceItemInfo(busServiceItem.getInfo());
        busCarPackageAudit.setServiceItemId(param.getServiceItemId());
        busCarPackageAudit.setServiceItemName(busServiceItem.getName());
        busCarPackageAudit.setServiceItemPrice(busServiceItem.getDiscountPrice());
        busCarPackageAudit.setStatus(CarPackageAuditStatusEnum.AUDITING.ordinal());
        return busCarPackageAudit;
    }
}
